<?php

	namespace org\tekuna\plugin\simplesecurity;
	
	use org\tekuna\base\Tekuna;

	use org\tekuna\core\context\Context;

	
	class ConfigUserProvider implements UserProvider {
		
		protected $arrUsers = array();

			
		public function initialize(Context $objContext) {
	
			$arrUserElements = $objContext 
								-> getConfiguration() 
								-> getRootElement() 
								-> getFirstChildElement('simple-security', 'security-config') 
								-> getAllChildElements('simple-security', 'user');
			
			foreach ($arrUserElements as $objUserElement) {
				
				// fill the User entity
				$objUser = new User();
				$objUser -> login = $objUserElement -> getAttribute('simple-security', 'login') -> getValue();
				$objUser -> encryptedPassword = $objUserElement -> getAttribute('simple-security', 'encrypted-password') -> getValue();
				$objUser -> name = $objUserElement -> getAttribute('simple-security', 'name') -> getValue();
				$objUser -> roles = explode(',', $objUserElement -> getAttribute('simple-security', 'roles') -> getValue());
				
				// register
				$this -> arrUsers[$objUser -> login] = $objUser;
			}
			
			// log known users
			Tekuna :: getLogger(__CLASS__) -> info("loaded users: ". implode(', ', array_keys($this -> arrUsers)));
		}
	
		
		public function getUser($sLogin) {
			
			// the user must exist
			if (! isset($this -> arrUsers[$sLogin])) {
				
				throw new SecurityException("The user '$sLogin' does not exist.");
			}
			
			return $this -> arrUsers[$sLogin];
		}
		
		
		public function encryptPassword($sLogin, $sPassword) {
			
			return base64_encode(sha1($sPassword . md5($sLogin), true));
		}
	}
